<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let jsonp = (url, data = {}, callback = 'callback') => {
            // 挂在window上
            let dataStr = url.indexOf('?') === -1 ? '?' : '&'
            // console.log(dataStr)
            for (let key in data) {
                dataStr += `${key}=${data[key]}&`
            }
            dataStr += 'callback=' + callback;
            let oScript = document.createElement('script');
            oScript.src = url + dataStr;
            document.body.appendChild(oScript);
            console.log(dataStr);

            // window[callback] = (data) => {
            //     console.log(data);
            // }
            return new Promise((resolve,reject) =>{
                window[callback] = (data) => {
                    try{
                        resolve(data)
                    } catch(e) {
                        reject(e)
                    } finally {
                        oScript.parentNode.removeChild(oScript);
                    }
                }
            })
        }


        // 请使用jsonp原理，封装json函数，不用再为了远程资源，1.加一个函数 2.加一个远程标签
        jsonp('https://photo.sina.cn/aj/index', {
            page: 1,
            cate: 'recommend'
        })
            .then(response => {
                console.log(response,'-------then');
            })
        
            jsonp('http://localhost:3000',{
                a:1,
                callback: 'funcA'
            })
    </script>
</body>

</html>